﻿using Nop.Admin.Models.XJ;
using Nop.Core;
using Nop.Core.Domain.XJ;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.ExportImport;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Services.XJ;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Admin.Controllers
{
	public class PlaceController : BaseAdminController
	{
		#region Fields
		private readonly IPermissionService _permissionService;
		private readonly IPictureService _pictureService;
		private readonly IWorkContext _workContext;
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJPlaceService _xjPlaceService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly IExportManager _exportManager;
		private readonly IImportManager _importManager;
		private readonly ILogger _logger;
		#endregion

		#region Constructors
		public PlaceController(IPermissionService permissionService,
			IPictureService pictureService,
			IWorkContext workContext,
			IDepartmentService departmentService,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			IXJPlaceService xjPlaceService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceCommentService xJMaintenanceCommentService,
			ICustomerActivityService customerActivityService,
			IExportManager exportManager,
			IImportManager importManager,
			ILogger logger)
		{
			this._permissionService = permissionService;
			this._pictureService = pictureService;
			this._workContext = workContext;
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._xjPlaceService = xjPlaceService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
			this._customerActivityService = customerActivityService;
			this._exportManager = exportManager;
			this._importManager = importManager;
			this._logger = logger;
		}
		#endregion

		#region Utilities

		#endregion

		#region List
		public ActionResult Index()
		{
			return RedirectToAction("List");
		}

		public virtual ActionResult List()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var model = new PlaceListModel();

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult PlaceList(DataSourceRequest command, PlaceListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedKendoGridJson();

			var places = _xjPlaceService.GetAllPlaces(
				name: model.SearchName,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = places.Select(x =>
				{
					var place = new PlaceModel
					{
						Id = x.Id,
						Name = x.Name,
						Location = x.Location,
						Longitude = x.Longitude,
						Latitude = x.Latitude,
						Point = string.Format("{0},{1}", x.Longitude ?? "", x.Latitude ?? ""),
						DisplayOrder = x.DisplayOrder,
						Published = x.Published,
						CustomerId = x.CustomerId,
						CreatedOn = x.CreatedOn,
					};
					return place;
				}),
				Total = places.TotalCount
			};
			return Json(gridModel);
		}

		[AcceptVerbs(HttpVerbs.Get)]
		public virtual ActionResult GetLocationById(int pid)
		{
			var place = _xjPlaceService.GetXJPlaceById(pid);
			return Json(place == null ? "" : place.Location);
		}
		#endregion

		#region Create / Edit / Delete

		public virtual ActionResult Create()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var model = new PlaceModel
			{
				Published = true
			};

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Create(PlaceModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				var equipment = new XJPlace
				{
					Name = model.Name,
					Location = model.Location,
					Longitude = model.Longitude,
					Latitude = model.Latitude,
					DisplayOrder = model.DisplayOrder,
					Published = model.Published,
					CustomerId = _workContext.CurrentCustomer.Id,
					CreatedOn = DateTime.Now,
				};
				_xjPlaceService.InsertXJPlace(equipment);

				//activity log
				_customerActivityService.InsertActivity("AddNewPlace", "新增巡检点：{0}", equipment.Name);

				SuccessNotification("保存成功");

				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = equipment.Id });
				}
				return RedirectToAction("List");
			}

			return View(model);
		}

		public virtual ActionResult Edit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var place = _xjPlaceService.GetXJPlaceById(id);
			if (place == null || place.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new PlaceModel
			{
				Id = place.Id,
				Name = place.Name,
				Location = place.Location,
				Longitude = place.Longitude,
				Latitude = place.Latitude,
				DisplayOrder = place.DisplayOrder,
				Published = place.Published,
				CustomerId = place.CustomerId,
				CreatedOn = place.CreatedOn,
			};

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Edit(PlaceModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var place = _xjPlaceService.GetXJPlaceById(model.Id);
			if (place == null || place.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			if (ModelState.IsValid)
			{
				place.Name = model.Name;
				place.Location = model.Location;
				place.Longitude = model.Longitude;
				place.Latitude = model.Latitude;
				place.DisplayOrder = model.DisplayOrder;
				place.Published = model.Published;
				_xjPlaceService.UpdateXJPlace(place);

				//activity log
				_customerActivityService.InsertActivity("EditPlace", "编辑巡检点：{0}", place.Name);

				SuccessNotification("保存成功");
				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = place.Id });
				}
				return RedirectToAction("List");
			}

			return View(model);
		}

		[HttpPost]
		public virtual ActionResult Delete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var equipment = _xjPlaceService.GetXJPlaceById(id);
			if (equipment == null)
				//No equipment found with the specified id
				return RedirectToAction("List");

			_xjPlaceService.DeletePlace(equipment);

			//activity log
			_customerActivityService.InsertActivity("DeletePlace", "删除巡检点：{0}", equipment.Name);

			SuccessNotification("删除成功");
			return RedirectToAction("List");
		}

		#endregion

		#region Export / Import

		[HttpPost, ActionName("List")]
		[FormValueRequired("exportexcel-all")]
		public virtual ActionResult ExportExcelAll(PlaceListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var places = _xjPlaceService.GetAllPlaces(
				name: model.SearchName);

			try
			{
				byte[] bytes = _exportManager.ExportPlacesToXlsx(places);
				return File(bytes, MimeTypes.TextXlsx, "巡检点.xlsx");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("List");
			}
		}

		[HttpPost]
		public virtual ActionResult ExportExcelSelected(string selectedIds)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			var places = new List<XJPlace>();
			if (selectedIds != null)
			{
				var ids = selectedIds
					.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
					.Select(x => Convert.ToInt32(x))
					.ToArray();
				places.AddRange(_xjPlaceService.GetPlacesByIds(ids));
			}

			try
			{
				byte[] bytes = _exportManager.ExportPlacesToXlsx(places);
				return File(bytes, MimeTypes.TextXlsx, "巡检点.xlsx");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("List");
			}
		}

		[HttpPost]
		public virtual ActionResult ImportFromXlsx()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManagePlaces))
				return AccessDeniedView();

			try
			{
				var file = Request.Files["importexcelfile"];
				if (file != null && file.ContentLength > 0)
				{
					_importManager.ImportPlacesFromXlsx(file.InputStream, _workContext.CurrentCustomer);
				}
				else
				{
					ErrorNotification("上传失败");
					return RedirectToAction("List");
				}
				SuccessNotification("上传成功");
				return RedirectToAction("List");
			}
			catch (Exception exc)
			{
				ErrorNotification(exc);
				return RedirectToAction("List");
			}
		}
		#endregion
	}
}